<!--  -->
<template>
  <div>
    <div v-if="requestError" class="text-c errorPlace">
      <img width="100px" height="100px" :src="require('@/assets/images/pic_neterror.png')" alt="获取数据失败" />
      <div class="color-b font14" style="margin: 10px 0 0 0">
        获取数据失败!
      </div>
      <van-button plain round size="small" color="#7232dd" type="primary" @click="getdetail">点击重试</van-button>
    </div>
    <van-form v-else @submit="submitFromData">
      <div class="font15 mt10 pl10">
        <span class="titletext">{{ detailData.title }}</span>
        <div class="graytext mt10 font13">
          <span>工单编号：</span>
          <span class="titletext">{{ fromdata.pmInsId }}</span>
        </div>
      </div>
      <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;">
        <div class="blue_item" />
        <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">{{ moduleFirstText }}</span>
      </div>
      <van-field readonly required name="city" :value="fromdata.city" label="地市：" label-width="3em" />
      <van-field readonly required name="counties" :value="fromdata.counties" label="县区：" label-width="3em" />
      <van-field readonly required name="sponsor" :value="fromdata.sponsor" label="发起人：" label-width="4em" />
      <van-field readonly required name="sponsorUsername" :value="fromdata.sponsorUsername" label="发起人OA账户："
        label-width="7.5em" />
      <van-field readonly required name="sponsorDate" :value="fromdata.sponsorDate" label="发起时间：" label-width="5em" />
      <van-field readonly required name="questionType" :value="fromdata.questionType" label="问题类型：" label-width="5em" />
      <van-field readonly required name="contactPerson" :value="fromdata.contactPerson" label="联系人：" label-width="4em" />
      <van-field readonly required name="contactPersonTel" :value="fromdata.contactPersonTel" label="联系方式："
        label-width="5em" />
      <van-field readonly required name="module" :value="fromdata.module" label="所属模块：" label-width="5em" />
      <van-field readonly required name="menu" :value="fromdata.menu" label="系统功能：" label-width="5em" />
      <van-field readonly required name="questionTitle" :value="fromdata.questionTitle" label="问题标题：" label-width="5em" />

      <div class="van-cell van-cell--required van-field">
        <div class="van-cell__title van-field__label" style="width: 5em;"><span>问题描述：</span></div>
        <div class="van-cell__value van-field__value">
          <div class="van-field__body">
            <div name="questionDescribe" class="van-field__control" v-html="formatter(this.fromdata.questionDescribe)">
            </div>
          </div>
        </div>
      </div>

      <van-field readonly name="isWA?workOrderFile:systemExceptionFile" label="附件：" label-width="3em" />
      <div v-for="(fileitem, index2) in isWA?fromdata.workOrderFile:fromdata.systemExceptionFile" :key="fileitem.id" style="margin-left: 20px">
        <div readonly class="font14 fileLink" style="color: #0f85cf">
          <a target="_blank" @click="openFileUrlfun(fileitem.anonymousFilePath)">{{ fileitem.fileName }}</a>
        </div>
      </div>

      <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;">
        <div class="blue_item" />
        <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">问题处理信息</span>
      </div>
      <van-field readonly name="questionBelongType" :value="fromdata.questionBelongType" label="问题类型："
        @click="getTypesAndShow" label-width="5em" placeholder="请选择" :right-icon='canEditHandleMethodModule?"arrow":""' />

      <van-popup v-model='showIsTypePop' round position="bottom" get-container="body">
        <van-picker show-toolbar  :columns="typeOptionsList" @cancel="showIsTypePop = false"
          @confirm="IsTypePopConfirm" />
      </van-popup>
      <span v-if="showTipWhenEditWithHtml" class="label-lesson">如需调整处理方法，请至PC端修改</span>

      <van-field v-if="textCanEdit" autosize type="textarea" rows="1" name="handleMethod" 
        v-model="fromdata.handleMethod" label="处理方法：" label-width="5em" />
        
      <div v-else  class="van-cell  van-field">
        <div class="van-cell__title van-field__label" style="width: 5em;"><span>处理方法：</span></div>
        <div class="van-cell__value van-field__value">
          <div class="van-field__body">
            <div name="handleMethod" class="van-field__control" v-html="formatter(this.fromdata.handleMethod)">
            </div>
          </div>
        </div>
      </div>


      <van-field readonly name="handleFile" label="处理附件：" label-width="5em" center>
        <template #button v-if="canEditHandleMethodModule">
          <van-uploader :after-read="file2server">
            <van-button size="small" type="primary" color="#0f85cf">上传附件</van-button>
          </van-uploader>
        </template>
      </van-field>
      <div v-for="(fileitem, index2) in fromdata.handleFile" :key="fileitem.id" style="margin-left: 20px">
        <div readonly class="font14 fileLink" style="color: #0f85cf">
          <a target="_blank" @click="openFileUrlfun(fileitem.anonymousFilePath)">{{ fileitem.fileName }}</a>
        </div>
        <van-icon v-if="canEditHandleMethodModule" name="close" color="#ea0023" size="20" @click="deleteFile(index2)" />
      </div>

      <div v-if="showModuleComment">
        <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;">
          <div class="blue_item" />
          <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">发起人评论</span>
        </div>
        <van-field readonly name="isFinish" :value="fromdata.isFinish" label="是否办结：" label-width="5em" right-icon='arrow'
          placeholder="请选择" @click="showBanjiePopMethod" />
        <van-popup v-model='showIsBanjiePop' round position="bottom" get-container="body">
          <van-picker show-toolbar  :columns="['是', '否']" @cancel="showIsBanjiePop = false"
            @confirm="IsBanjiePopConfirm" />
        </van-popup>
        <van-field readonly name="evaluate" :value="fromdata.evaluate" label="发起人评价：" label-width="6em" right-icon='arrow'
          placeholder="请选择" @click="showManyiPopMethod" />
        <van-popup v-model='showIsManyiPop' round position="bottom" get-container="body">
          <van-picker show-toolbar  :columns="['满意', '不满意']" @cancel="showIsManyiPop = false"
            @confirm="IsManyiPopConfirm" />
        </van-popup>
        <van-field v-if="fromdata.evaluate == '不满意'" required autosize type="textarea" rows="1" name="evaluateReason"
          v-model="fromdata.evaluateReason" label="不满意原因：" label-width="6em" :readonly="showHistory"
          :rules="[{ required: true, message: '请填写不满意原因' }]" />
      </div>
      <div v-if="todotype==true||toread==true" class="footer">
        <van-button block type="info" native-type="submit" :disabled="canNextInMobile?false:true"
          style="display: inline-block;width:100%;border: 0px solid #60a9ec;">{{ sumitBottonText }}</van-button>
      </div>
    </van-form>
    <historyAndSuggs :showHistory='showHistory' :historydata='historydata' :approveList='approveList' />
  </div>
</template>

<script>
import { getSrqrRequest, getFormDetail, uploadFileCommon, wfWorkItemModel, getWfOptMags } from '@/api/dictapi'
import util from "@/assets/js/public";
import { mapGetters } from "vuex"
import { Notify, Dialog, Toast } from "vant";
import { openFileUrl } from "@/store/openFile";
import historyAndSuggs from "@/views/srqr/historyAndSuggs.vue"
export default {
  data() {
    return {
      active: 0,
      requestError: false,
      params: this.$route.query,
      isWA:this.$route.query.pmInsId.startsWith("WA") ,
      showHistory: false,
      showIsBanjiePop: false,
      showIsManyiPop: false,
      showIsTypePop: false,
      canNextInMobile: true,//当前环节是否可在手机端办理
      showModuleComment: false,//是否显示发起人评论模块
      canEditHandleMethodModule:true,//问题处理模块是否可编辑
      historydata: {},//已办显示当前办理人
      fromdata: {
        handleMethod: '',
        evaluateReason: ''
      },//详情信息
      detailData: {},//详情信息,没啥用，但是服务器递交需要id不得不调用这个接口
      typeOptionsList: [],//问题类型
      approveList: [],//审批意见列表
       todotype:false,
      toread:false,
    }
  },
  computed: {
    ...mapGetters(['user']),
    ...mapGetters(['userinfo']),
    moduleFirstText: function () {
      if (this.isWA) {
        return "问题描述信息";
      } else {
        return "系统异常反馈";
      }
    },
    sumitBottonText: function () {
      if (this.canNextInMobile) {
        return "流转下一步";
      } else {
        return "暂不支持该环节,请至PC端办理";
      }
    },
    showTipWhenEditWithHtml: function () {
      if (!this.canEditHandleMethodModule) return false;
      if (this.fromdata.handleMethod === null) this.fromdata.handleMethod = '';
      if (typeof (this.fromdata.handleMethod) === 'string') {
        let empty = this.fromdata.handleMethod == '';
        let noHtml = this.fromdata.handleMethod.indexOf('/&(lt|gt|nbsp|amp|quot);/gi') == -1;
        return !empty && !noHtml;
      }
      return false;
    },
    textCanEdit: function () {
      if (!this.canEditHandleMethodModule) return false;
      if (this.fromdata.handleMethod === null) this.fromdata.handleMethod = '';
      if (typeof (this.fromdata.handleMethod) === 'string') {
        let empty = this.fromdata.handleMethod == '';
        let noHtml = this.fromdata.handleMethod.indexOf('/&(lt|gt|nbsp|amp|quot);/gi') == -1;
        return empty || noHtml;
      }
      return false;
    },
  },
  components: {
    historyAndSuggs
  },
  //生命周期--创建完成
  created() {
    if(this.params.pmInsType==null&&this.params.processType!=null) {
          this.params.pmInsType = this.params.processType
        }
    if (this.params.todoType % 2 == 0) {
      this.showHistory = true;
      this.canEditHandleMethodModule =false;
    }else if (this.params.todoType % 3 == 0) {
      this.toread = true;
    }else{
      this.todotype = true;
    }
    if (this.params.location == 'dict.start') {
      this.canNextInMobile = false;
      this.canEditHandleMethodModule =false;
    }
    if (this.params.location == 'dict.oneLineToEvaluate') {
      this.showModuleComment = true;
      this.canEditHandleMethodModule =false;
    }
    this.params.userName = this.user.userName;
    this.getdetail();
  },
  //方法调用
  methods: {
    //获取数据字典，如果存在直接显示pop，不存在则请求
    getTypesAndShow() {
      if (!this.canEditHandleMethodModule ) return;
      if (this.typeOptionsList.length > 0) {
        this.showIsTypePop = true;
        return;
      } else {
        this.queryByType();
      }
    },
    showBanjiePopMethod: function () {
      if (this.showHistory) return;
      this.showIsBanjiePop = true;
    },
    showManyiPopMethod: function () {
      if (this.showHistory) return;
      this.showIsManyiPop = true;
    },
    deleteFile(index) {
      Dialog.confirm({
        title: "提示",
        message: "是否删除此附件？",
      })
        .then(() => {
          this.fromdata.handleFile.splice(index, 1);
        })
        .catch(() => { });
    },
    IsTypePopConfirm(value) {
      this.showIsTypePop = false;
      this.fromdata.questionBelongType = value;
    },
    //打开附件
    openFileUrlfun(value) {
      this.$router.push({
        name: "fileview",
        query: {
          openFileUrl: openFileUrl(value),
        },
      });
    },
    IsManyiPopConfirm(value) {
      this.showIsManyiPop = false;
      this.fromdata.evaluate = value;
    },
    IsBanjiePopConfirm(value) {
      this.showIsBanjiePop = false;
      this.fromdata.isFinish = value;
    },
    //富文本转义
    formatter(str) {
      if (typeof (str) === 'string') {
        var arrEntities = { lt: "<", gt: ">", nbsp: " ", amp: "&", quot: '"' };
        return str.replace(/&(lt|gt|nbsp|amp|quot);/gi, function (all, t) {
          return arrEntities[t];
        });
      }
      return '';
    },
    //返回
    goBack() {
      this.$router.back(-1) //返回上一页
    },
    //请求出错
    onError(result) {
      this.requestError = true;
      Toast.clear();
      Notify(result.message);
    },
    //获取详情
    getdetail() {
      Toast.loading({
        message: '加载中',
        forbidClick: false
      });
      getFormDetail(this.params).then((result) => {
        if (!result.data) {
          Toast.clear();
          this.onError(result);
          return;
        }
        if (result.data.data) {
          this.detailData = result.data.data;
          this.getFormData();
        }

      })

    },
    getFormData() {
      getSrqrRequest(this.isWA?'systemWorkOrderManage$api$getSystemWorkOrderManageByPmInsId':"systemExceptionManage$api$getSystemExceptionManageByPmInsId", Object.assign(this.params, {
        kv: {
          "source": 'MOBILE',
          "pmInsId": this.params.pmInsId,
          "currentUserCode": util.encrypt(this.params.userName),
        }
      })
      ).then((result) => {
        Toast.clear();
        if (!result.data) {
          this.onError(result);
          return;
        }
        if (result.data.data) {
          this.fromdata = result.data.data;
          if (this.showModuleComment) {//评价部分设置默认值
            if (this.fromdata.isFinish == null) {
              this.fromdata.isFinish = '是'
            }
            if (this.fromdata.evaluate == null) {
              this.fromdata.evaluate = '满意'
            }
          }
          if (this.showHistory) {
            this.wfWorkItemModel();
          }
          this.getWfOptMags();
        }

      })
    },
    queryByType() {//数据字典
      Toast.loading({
        message: '加载中',
        forbidClick: false
      });
      getSrqrRequest('queryDictValue$api$queryByType', Object.assign(this.params, {
        kv: {
          "source": 'MOBILE',
          "dictType": "questionType",
          "currentUserCode": util.encrypt(this.params.userName),
        }
      })
      ).then((result) => {
        Toast.clear();
        if (!result.data) {
          Notify(result.message);
          return;
        }
        if (result.data.data) {
          this.typeOptionsList = result.data.data.map((item, index) => {
            return item.name;
          });
          this.showIsTypePop = true;
        }
      })
    },
    file2server(file) {
      let fileData = new FormData();
      fileData.append("pmInsType", this.params.pmInsType);
      fileData.append("pmInsTypePart", "1");
      fileData.append("files", file.file);
      this.params.pmInsTypePart = '1';
      uploadFileCommon(fileData, this.params).then((res) => {
        if (!res.data) {
          Notify(res.message);
          return;
        }
        if (res.data.data) {
          if (this.fromdata.handleFile === null) {
            this.fromdata.handleFile = [];
          }
          this.fromdata.handleFile.push(res.data.data.sysFiles[0]);
        }
      });
    },
    //获取已办下一处理人
    wfWorkItemModel() {
      wfWorkItemModel(this.params)
        .then((result) => {
          if (!result.data) {
            Notify(result.message);
            return;
          }
          if (result.data.data) {
            this.historydata = result.data.data
            this.historydata.MANAGER = this.historydata.participantName || '暂无';
            this.historydata.DEPARTMENT = this.historydata.workItemName || '暂无';
          }
        })
    },
    //获取审批意见
    getWfOptMags() {
      getWfOptMags(this.params)
        .then((result) => {
          if (!result.data) {
            Notify(result.message);
            return;
          }
          this.approveList = result.data.data.reverse();
        })
    },
    //下一步流转
    submitFromData() { //提交流转
      if (this.fromdata.handleFile) {
        this.fromdata.handleFileId = '';
        this.fromdata.handleFile.forEach((item, index) => {
          if (index == this.fromdata.handleFile.length - 1) {
            this.fromdata.handleFileId += item.id;
          } else {
            this.fromdata.handleFileId += item.id + ",";
          }
        })
      }
      var formSendData = { "htmlParamMap": {} };
      formSendData.htmlParamMap = this.fromdata;
      formSendData.id = this.detailData.id;
      formSendData.pmInsId = this.params.pmInsId;
      formSendData.processType = this.params.pmInsType
      formSendData.workItemId = this.params.workItemId;

      var params1 = {
        kv: {
          currentUserCode: util.encrypt(this.params.userName),
          source: 'MOBILE',
          location: this.params.location,
          processInstId: this.params.processInstId,
          processDefName: this.params.processDefName,
          processType: this.params.pmInsType,
        },
      };
      var params2 = {
        kv: {
          "currentUserCode": util.encrypt(this.params.userName),
          "source": 'MOBILE',
          "location": this.params.location,
          "processInstId": this.params.processInstId,
          'processType': this.params.pmInsType,
          'receiptCode': this.params.processInstId
        },
      };
      var params3 = {
        kv: {
          "source": 'MOBILE',
          "currentUserCode": util.encrypt(this.params.userName),
          "workItemId": this.params.todoType==3?"":this.params.workItemId,
          "processInstId": this.params.processInstId,
          "location": this.params.location,
          "notificationId":this.params.todoType==3?this.params.wfnid:""
        },
      };
      localStorage.setItem('submitPageParam', JSON.stringify({
        getDecisionsUrl: 'decisionAndUser$api$getDecisions',
            getDecisionsParams: params1,
            getUserUrl: 'decisionAndUser$api$getOrgAndUser',
            getUserParams: params2,
            tosubmintUrl: 'applicationFormEnhance$api$startSubmitProcess',
            tosubmintParams: params3,
            formData: formSendData,
            fromMoa:this.params.fromMoa,
            type:this.params.todoType==3?"toRead":"toDo"
          }))
      this.$router.push(
        {
          name: 'srqrsubmit'
        }
      );
    },

  }
}
</script>
<style  scoped>
.errorPlace {
  position: absolute;
  margin-top: -80px;
  top: 50%;
  margin-left: -50px;
  left: 50%;
}

.file-list {
  border: 1px solid #60a9ec;
  margin: 5px 10px 5px 10px;
  padding: 5px 0px 5px 0px;
  border-radius: 10px;
}

.label-lesson {
  padding-left: 15px;
  color: #ea0023;
  font-size: 12px;
}
</style>
